<template>
  <div class="container login-container">
    <header class="drag" style="font-size: 20px">微信</header>
    <el-form class="form" :model="form" ref="formRef" :rules="rules">
      <el-form-item prop="email">
        <el-input style="border: none" v-model.trim="form.email" size="large" clearable placeholder="请填写邮箱">
          <template #prefix>
<!--            <span class="iconfont icon-email"></span>-->
            <el-icon><Message /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="nickname" v-if="!isLogin">
        <el-input style="border: none" v-model.trim="form.nickname" :maxlength="10" size="large" clearable placeholder="请填写昵称">
          <template #prefix>
<!--            <span class="iconfont icon-user-nick"></span>-->
            <el-icon><EditPen /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input show-password style="border: none" :maxlength="18" v-model.trim="form.password" size="large" clearable placeholder="请填写密码">
          <template #prefix>
<!--            <span class="iconfont icon-password"></span>-->
            <el-icon><Key /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="passwordConfirm" v-if="!isLogin">
        <el-input show-password style="border: none" :maxlength="18" v-model.trim="form.passwordConfirm" size="large" clearable placeholder="请再次填写密码">
          <template #prefix>
<!--            <span class="iconfont icon-password"></span>-->
            <el-icon><Key /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <span class="iconfont icon-checkcode"></span>
      <el-form-item prop="code">
        <el-input class="inputDeep" style="border: none" :maxlength="6" v-model.trim.number="form.code" size="large" clearable placeholder="请填写验证码">
          <template #prefix>
<!--            <span class="iconfont icon-checkcode"></span>-->
            <el-icon><Cellphone /></el-icon>
          </template>
          <template #suffix>
<!--            <span class="iconfont icon-checkcode"></span>-->
            <el-button @click="getEmailCode" type="success" link  :disabled="isGet || !/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(form.email)">
              {{isGet? `${codeTime}秒后重新获取`: '获取'}}
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button :loading="isLoading" class="login-btn" @click="loginOrRegister" type="primary"> {{ isLogin ? '登录' : '注册' }}</el-button>
      </el-form-item>

      <el-form-item>
        <div class="register-btn-container">
          <el-button type="primary" link @click="handleChange" v-text="isLogin ? '没有账号?' : '已有账号?'"></el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {useUserStore} from '@/stores/user'
import { ElMessage } from 'element-plus'
import {useRouter} from 'vue-router'
import { EditPen, Key, Message , Cellphone } from '@element-plus/icons-vue'
import { getCode, reqUserInfoByOwner } from '@/api/user'
import ws from '@/webSocket'
import { useSystemStore } from '../stores/system'

const userStore = useUserStore()
const systemStore = useSystemStore()
const router = useRouter()

const isLogin = ref(true)
const form = ref({
  email: '1472939313@qq.com',
  code: 8888,
  password: 123456
})
const formRef = ref(null)
const isLoading = ref(false)
const isGet = ref(false)
const codeTime = ref(0)

// 表单校验规则
const rules = {
  email: [
    { validator: (rule , value , callBack) =>{
        if (!value) {
          callBack(new Error("请填写邮箱!"))
          return
        }  else {
          if (/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(value)) {
            callBack()
          } else {
            callBack(new Error("请填写正确格式的邮箱!"))
          }

        }
      }  , trigger: 'change'}
  ],
  password: [
    {required : true , message : '请填写密码!' , trigger: 'change'}
  ],
  passwordConfirm: [
    { validator : (rule , value , callBack) => {
      if (value) {
        if (value === form.value.password) {
          callBack()
        } else {
          callBack('两次密码输入不一致!')
        }

      } else {
        callBack(new Error("请再次填写密码!"))
      }

      } , trigger : 'change' }
  ],
  nickname: [
    {required : true , message : '请填写昵称!' , trigger: 'change'}
  ],
  code: [
    {required : true , message : '请填写验证码!' , trigger: 'change'}
  ],

}


// 获取验证码
const getEmailCode = ()=> {
  getCode({email:form.value.email}).then(res=>{
    if (res.code === 200) {

      codeTime.value = 60
      isGet.value = true
      const id = setInterval(() => {
        if (codeTime.value <= 0) {
          clearInterval(id)
          isGet.value = false
          return
        }
        codeTime.value--
      } , 1000)


      ElMessage.success(
        {
          type: 'success',
          message: '验证码已发送'
        }
      )

    }
  })

}

// 登录或注册方法
const loginOrRegister = () => {
  isLoading.value = true
  formRef.value.validate(async result => {
    if (result) {
      // 如果是登录
      if (isLogin.value) {
        try {
          const token = await userStore.login(form.value)
          userStore.userInfo().then(res =>{
            const data = res
            ws.initWebSocket()

            window.ipcRenderer.send('openChat' , {
              email: data.email,
              token: token,
              userId:data.uid,
              nickName: data.nickname,
              admin:false,
              screenWidth: window.screen.width,
              screenHeight: window.screen.height
            })
            systemStore.showLoading = true

            router.push('/main')
          })

        } catch (e) {
          ElMessage({
            message: e.message,
            type: 'error',
          })
        }



      } else {
        // 如果是注册

      }
    }


  })

  isLoading.value = false
}

// 切换登录注册
const handleChange = () => {

  isLogin.value = !isLogin.value
  formRef.value.clearValidate()
  formRef.value.resetFields()
  window.ipcRenderer.send('handleLoginOrRegister' , isLogin.value)


}

</script>


<style scoped lang="less">
.login-container {
  flex-direction: column;
  padding: 15px 20px;

  header {
    margin-bottom: 20px;
  }

  .form {
    .el-icon {
      font-size: 18px;
    }
  }

  :deep(.el-input__wrapper) {
    box-shadow: 0 -1px 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
    border-radius: 0px;
    cursor: default;
    .el-input__inner {
      cursor: default !important;
    }
  }

  .login-btn {
    width: 100%;
  }

  .register-btn-container {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }


}


</style>
